package com.team2.shoppingService;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.team2.shared.ServerProduct;
import com.team2.shared.ServerStore;

public class WebParserShoppingRequest extends ShoppingRequest {
	/**
	 * 
	 * @param source the website that used to parse. E.g. Future shop, Bestbuy
	 * @param tags   the string used for keyword search
	 */
	public WebParserShoppingRequest(String source,
			String tags) {
		super();
		tags = tags.trim();
		tags = tags.replace(' ', '+');
		this.source = source;
		this.tags = tags;
		this.configFile = Configuration.getParserConfig(source);
		webParser = new WebHarvest();
	}

	private String configFile;
	private String source; // the website that used to parse. E.g. Future shop, Bestbuy
	private WebHarvest webParser;
	@Override
	public ArrayList<ServerProduct> execute() {
		// TODO Auto-generated method stub
		ArrayList<ServerProduct> products = new ArrayList<ServerProduct> ();
		String xmlString = webParser.GetProductCatalog(tags, configFile);
		//System.out.println(xmlString);
		products = parseProductXML(xmlString);
		return products;
	}
	private ArrayList<ServerProduct> parseProductXML(String xmlString){
		ArrayList<ServerProduct> products = new ArrayList<ServerProduct>();
		
		if(xmlString==null||xmlString.isEmpty()) return products;
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
		DocumentBuilder builder;  
		try  
		{  
			builder = factory.newDocumentBuilder();  
			Document document = builder.parse( new InputSource( new StringReader( xmlString ) ) );  
			org.w3c.dom.NodeList nodeList = document.getElementsByTagName("product");

			if(nodeList != null && nodeList.getLength() > 0) {
				for(int i = 0 ; i < nodeList.getLength();i++) {

					Element el = (Element)nodeList.item(i);
					ServerProduct product = new ServerProduct();
					product.setTitle(el.getElementsByTagName("title").item(0).getFirstChild().getNodeValue());
					product.setImageLink(el.getElementsByTagName("image").item(0).getFirstChild().getNodeValue());
					product.setPrice(el.getElementsByTagName("price").item(0).getFirstChild().getNodeValue());
					product.setProvider(this.source);
					product.setLink(el.getElementsByTagName("link").item(0).getFirstChild().getNodeValue());
					String description = "";
					NodeList list = el.getElementsByTagName("description");
					Node tempNode;
					if(list.getLength()>0){
						tempNode = list.item(0).getFirstChild();
						if (tempNode!=null){
							description = tempNode.getNodeValue();
						}
					}
					product.setDescription(description);
					
					list = el.getElementsByTagName("modelNumber");
					if(list.getLength()>0){
						tempNode = list.item(0).getFirstChild();
						if (tempNode!=null){
							product.setModelNumber(tempNode.getNodeValue());
						}
					}
					tempNode = el.getElementsByTagName("storeAvailablity").item(0).getFirstChild();
					product.setInStoreAvailability(tempNode==null ? "":tempNode.getNodeValue());
					
					tempNode = el.getElementsByTagName("onlineAvailablity").item(0).getFirstChild();
					product.setOnlineAvailablility(tempNode==null ? "":tempNode.getNodeValue());
					
					
					//set store information
					ServerStore store = new ServerStore();
					store.setBrand(this.source);
					store.setPrice(product.getPrice());
					product.getStores().add(store);
					products.add(product);
					//System.out.println(product.getTitle());
					
				}
			}
		} catch (Exception e) {  
			e.printStackTrace();  
		} 
		return products;
	}
	private void test(){
		long startTime = System.currentTimeMillis();

		final String futureShopCatalog = "WebParserConfigFiles/futureShopCatalog.xml";
		final String chaptersCatalog = "WebParserConfigFiles/chaptersCatalog.xml";
		final String walmartCatalog = "WebParserConfigFiles/walmartCatalog.xml";
		final String searsCatalog = "WebParserConfigFiles/searsCatalog.xml";
		final String theBayCatalog = "WebParserConfigFiles/theBayCatalog.xml";
		final String bestBuyCatalog = "WebParserConfigFiles/bestBuyCatalog.xml";
		
		WebHarvest obj = new WebHarvest();
		
		String futureShopProdCatalog = obj.GetProductCatalog("fridge", futureShopCatalog);
		
		//Printing the scraped data here
		System.out.println(futureShopProdCatalog);
		
		String chaptersProdCatalog = obj.GetProductCatalog("steve+jobs", chaptersCatalog);
		
		//Printing the scraped data here
		System.out.println(chaptersProdCatalog);
		
		String walmartProdCatalog = obj.GetProductCatalog("apple+ipod", walmartCatalog);
		
		//Printing the scraped data here
		System.out.println(walmartProdCatalog);
		
		String searsProdCatalog = obj.GetProductCatalog("nike+shoes", searsCatalog);
		
		//Printing the scraped data here
		System.out.println(searsProdCatalog);
		
		String theBayProdCatalog = obj.GetProductCatalog("calvin+klein+men+shoes", theBayCatalog);
		
		//Printing the scraped data here
		System.out.println(theBayProdCatalog);	
		
		String bestBuyProdCatalog = obj.GetProductCatalog("apple+ipod", bestBuyCatalog);
		
		//Printing the scraped data here
		System.out.println(bestBuyProdCatalog);
		
		long stopTime = System.currentTimeMillis();
	    long elapsedTime = stopTime - startTime;
	    int seconds = (int) (elapsedTime / 1000) % 60 ;
	    int minutes = (int) ((elapsedTime / (1000*60)) % 60);
	    int hours   = (int) ((elapsedTime / (1000*60*60)) % 24);
	    System.out.printf("Hours = %d, Minutes = %d, Seconds = %d",hours, minutes, seconds);
	}


	public String getConfigFile() {
		return configFile;
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getTags() {
		return tags;
	}

	public void setTags(String tags) {
		this.tags = tags;
	}

}
